//
//  VSAddFoodViewController.m
//  孕妙
//
//  Created by 是源科技 on 16/8/22.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "VSAddFoodViewController.h"
#import "VSinformationViewController.h"
#import "foodExchange.h"



@interface VSAddFoodViewController ()<UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic,assign)CGFloat y;
@property (nonatomic,weak)UITextField *searchTextField;
@property (nonatomic,weak)UICollectionView *collcetionView;
@property (nonatomic,assign)int indexCount;
@property (nonatomic,assign)BOOL huadongFlag;

@property (nonatomic,strong)NSMutableArray *foodMutableArray;
@property (nonatomic,strong)NSMutableArray *imageArrayM;
@property (nonatomic,strong)NSMutableArray *titleArrayM;

@property (nonatomic,weak)UILabel *xialaLabel;


@end

@implementation VSAddFoodViewController

-(UILabel *)xialaLabel
{
    if(!_xialaLabel)
    {
        UILabel *xialaLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, kDeviceHeight - 50, kDeviceWidth , 30)];
        xialaLabel.text = @"松手,加载更多数据!!";
        xialaLabel.textAlignment = NSTextAlignmentCenter;
        xialaLabel.font = [UIFont systemFontOfSize:14.0f];
        xialaLabel.textColor = YMColor(91, 91, 91);
        _xialaLabel = xialaLabel;
        [self.view addSubview:xialaLabel];
        xialaLabel.hidden = YES;
    }
    return _xialaLabel;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加食物";
    self.view.backgroundColor = YMColor(245, 245, 245);
    [self searchTextFieldAndSearchButtonLayout];
    self.foodMutableArray = [NSMutableArray array];
    
    self.imageArrayM = [NSMutableArray array];
    self.titleArrayM = [NSMutableArray array];
    self.indexCount = 0;
    
    self.automaticallyAdjustsScrollViewInsets = NO; //控件无故偏移
    
    //初始化
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(5, self.y , kDeviceWidth - 10, kDeviceHeight - self.y) collectionViewLayout:flowLayout];
    self.collcetionView = collectionView;
    //注册
    //    [collectionView registerClass:[CollectionViewCell class]forCellWithReuseIdentifier:@"collectionCell"];
    [self.collcetionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    [self.view addSubview:collectionView];
    //    collectionView.backgroundColor = YMColor(245, 245, 245);
    collectionView.backgroundColor = [UIColor whiteColor];
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    
}

/**搜索条和搜索按钮布局*/
-(void)searchTextFieldAndSearchButtonLayout
{
    self.y = 74;
    UITextField *searchTextField = [[UITextField alloc]initWithFrame:CGRectMake(20, self.y, kDeviceWidth - 80, 30)];
    searchTextField.layer.cornerRadius = 8.0;
    searchTextField.layer.borderWidth = 1.0f;
    searchTextField.layer.borderColor = [YMColor(239, 180, 205)CGColor];
    searchTextField.textColor = YMColor(110, 110, 110);
    [searchTextField setValue:YMColor(206, 206, 206) forKeyPath:@"_placeholderLabel.textColor"];
    searchTextField.placeholder = @"请输入食物名称";
    searchTextField.delegate = self;
    self.searchTextField = searchTextField;
    searchTextField.clearButtonMode = UITextFieldViewModeAlways;
    searchTextField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:searchTextField];
    
    UIButton *searchButton = [[UIButton alloc]initWithFrame:CGRectMake(kDeviceWidth - 47, self.y + 4, 28, 28)];
    [searchButton setImage:[UIImage imageNamed:@"搜索btn"] forState:UIControlStateNormal];
    [self.view addSubview:searchButton];
    [searchButton addTarget:self action:@selector(clickSearchButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.y += searchTextField.frame.size.height + 10;
    
}

-(void)clickSearchButton
{
    YMLog(@"点击了搜索按钮");
    
    [self.searchTextField resignFirstResponder];
    if(![self.searchTextField.text isEqualToString:@""])
    {
        self.foodMutableArray = [NSMutableArray array];
        self.huadongFlag = NO;
        self.xialaLabel.hidden = NO;
        self.indexCount = 0;
        [self getFoodImageFromServicesWithIndexCount:self.indexCount andFoodName:self.searchTextField.text];
    }
    else
    {
        [MBProgressHUD showError:@"请输入要搜索的食物!"];
    }
}

/**从网上下载食物图片*/
-(UIImage *)downimageFromInternet:(NSString *)str
{
    NSURL *url = [NSURL URLWithString:str];
    NSData *resultData1 = [NSData dataWithContentsOfURL:url];
    UIImage *img1 = [UIImage imageWithData:resultData1];
    return img1;
}


/**从服务器上获取搜索到的食物*/
-(void)getFoodImageFromServicesWithIndexCount:(int)indexCount andFoodName:(NSString *)foodName;
{
    self.indexCount ++;
    //    YMLog(@"self.indexCount = %d",self.indexCount);
    [MBProgressHUD showMessage:@"正在拼命加载中，请稍后..."];
    
    NSString *urlString = @"http://120.24.178.16:8080/Health/food/findFoodsByName.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"pageSize=35&pageIndex=%@&foodName=%@",[NSString stringWithFormat:@"%d",indexCount],[NSString stringWithFormat:@"%@",foodName]];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data)
        {
            [MBProgressHUD hideHUD];
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            //            YMLog(@"dict = %@",dict);
            if([[dict objectForKey:@"code"] isEqualToString:@"0"])
            {
                NSArray *dataarray = [dict objectForKey:@"data"];
                if(dataarray.count > 0)
                {
                    //                    self.foodMutableArray = [NSMutableArray array];
                    for (NSDictionary *food in dataarray) {
                        foodExchange *fff = [foodExchange foodInfoWithDict:food];
                        [self.foodMutableArray addObject:fff];
                    }
                    
                    [UIView animateWithDuration:0.01 animations:^{
                        [self.collcetionView reloadData];
                    }];
                }
            }
            else
            {
                [MBProgressHUD showError:[dict objectForKey:@"message"]];
                self.indexCount --;
            }
            
            if([[dict objectForKey:@"code"]isEqualToString:@"1"])
            {
                [MBProgressHUD showError:@"数据已加载完毕!!!"];
                self.huadongFlag = YES;
            }
            
        }
    }];
}

//将图片存到数组中
-(void)addImageToArrayMAndAddTitleToTitleArrayM
{
    for (foodExchange *fff in self.foodMutableArray) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            UIImage *image = [self downimageFromInternet:fff.imgSrc];
            dispatch_async(dispatch_get_main_queue(), ^{
                //加载图片
                [self.imageArrayM addObject:image];
                //设置label文字
                
            });
            [self.titleArrayM addObject:fff.name];
        });
        
    }
    
}


//每个section的item个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.foodMutableArray.count;
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * CellIdentifier = @"UICollectionViewCell";
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    foodExchange *fff = self.foodMutableArray[indexPath.item];
    CGFloat w = cell.frame.size.width;
    CGFloat h = cell.frame.size.height;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, w, w)];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, w, w, h - w)];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:14.0f];
    label.textColor = YMColor(95, 95, 95);
    
    NSURL *url = [[NSURL alloc]initWithString:fff.imgSrc];
    [imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"zonghe"]];
    
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    //    UIImage *cachedImage = [manager imageWithURL:url]; // 将需要缓存的图片加载进来
    [manager downloadImageWithURL:url options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
        //        NSLog(@"显示当前进度");
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        
        //        NSLog(@"下载完成");
        //        imageView.image = image;
        
    }];
    
    
    
    
    label.text = fff.name;
    
    
    for (id subView in cell.contentView.subviews)
    {
        [subView removeFromSuperview];
    }
    [cell.contentView addSubview:label];
    [cell.contentView addSubview:imageView];
    
    [cell sizeToFit];
    
    return cell;
}



#pragma mark -- UICollectionViewDelegate
//设置每个 UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat w = self.collcetionView.frame.size.width;
    CGFloat spaceX = 2.0f;
    CGFloat lw = (w - spaceX * 5) / 5.0;
    CGFloat lh = lw + 25;
    return CGSizeMake(lw, lh);
}
//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0,0);
}

//定义每个UICollectionView 的纵向间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}


-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@",@(indexPath.row).description);
    
    foodExchange *fff = self.foodMutableArray[indexPath.row];
    [self.navigationController popViewControllerAnimated:YES];
    [passValue passValue].selectFood = fff;
}

#pragma mark - UIScrollViewDelegate实现方法-
// scrollView滚动时执行
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.y >= fmaxf(.0f, scrollView.contentSize.height - scrollView.frame.size.height) + 50) //x是触发操作的阀值
    {
        //触发上拉刷新
        if(self.huadongFlag == NO)
        {
            self.xialaLabel.hidden = NO;
        }
    }
    else
    {
        self.xialaLabel.hidden = YES;
    }
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //    NSLog(@"scrollViewWillBeginDragging");
    //    [self.foodMutableArray removeAllObjects];
    
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView.contentOffset.y >= fmaxf(.0f, scrollView.contentSize.height - scrollView.frame.size.height) + 50) //x是触发操作的阀值
    {
        if(self.huadongFlag == NO)
        {
            [self getFoodImageFromServicesWithIndexCount:self.indexCount andFoodName:self.searchTextField.text];
        }
    }
}





@end
